package com.fancy.learncenter.ui.activity;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.AddDiscussDataBean;
import com.fancy.learncenter.bean.FFlibraryStoryBean;
import com.fancy.learncenter.bean.GoldLectureInfoBean;
import com.fancy.learncenter.common.LoginUserSharePrefernce;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.ui.adapter.Album4Adapter;
import com.fancy.learncenter.ui.adapter.FragmentShowVideoAdapter;
import com.fancy.learncenter.ui.adapter.GoldLectureInfoAlbumAdapter;
import com.fancy.learncenter.ui.adapter.GoldLecturePersonalAdapter;
import com.fancy.learncenter.ui.callback.AlbumImpl;
import com.fancy.learncenter.ui.view.CustomFootView;
import com.fancy.learncenter.ui.view.CustomHeaderView;
import com.fancy.learncenter.ui.view.SharePopupWindow;
import com.fancy.learncenter.utils.ImgFilter;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.ProgressUtil;
import com.fancy.learncenter.utils.StrUtil;
import com.fancy.learncenter.utils.Utils;
import com.fancy.learncenter.utils.WXShareUtil;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Response;
import rx.Subscriber;

/**
 * 金牌讲师
 */
public class GoldLecturerActivity extends BaseActivity {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.right)
    TextView right;
    @Bind(R.id.right_img)
    ImageView rightImg;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.gold_lecture_recycle)
    RecyclerView goldLectureRecycle;
    @Bind(R.id.xRefreshView)
    XRefreshView xRefreshView;

    SimpleDraweeView headView;
    TextView headName;
    TextView headLevel;
    TextView kindergartenNameTxt;
    TextView decription;
    ImageView vipImage1;
    ImageView vipImage2;
    ImageView vipImage3;
    TextView infoDown; //完全简介下标
    RecyclerView albumRecycleFull; //全部图片
    RecyclerView albumRecyle4;    //4张图片
    FrameLayout albumRecycleLayout;
    View topView;
    GoldLectureInfoAlbumAdapter adapter;
    Album4Adapter album4Adapter;
    GoldLecturePersonalAdapter personalAdapter;
    private String fid;
    Dialog dialog;
    GoldLectureInfoBean infoBean;
    List<String> list = new ArrayList<>();
    List<String> list4 = new ArrayList<>();
    List<FFlibraryStoryBean.ResultBean> storyList = new ArrayList<>();
    boolean isShow4 = false;
    private int PageIndex = 1;
    String nickName = "";
    int memberType;
    boolean flag = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gold_lecturer, Status.STATUS, "");
        ButterKnife.bind(this);
        getIntentData();
        initView();
        initRecycle();
        initXRefresh();
        getUserInfo();
        getStoryData();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (personalAdapter.audioPlayer != null){

            personalAdapter.audioPlayer.stop();
       }
    }

    private void getIntentData() {
        fid = getIntent().getStringExtra("fid");
        nickName = getIntent().getStringExtra("nick_name");
    }

    private void isExpand(){

        if (decription.getLineCount() < 3){
            decription.setMaxLines(Integer.MAX_VALUE);
            decription.setEllipsize(null);
            infoDown.setText("收起");
            infoDown.setVisibility(View.VISIBLE);
            infoDown.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.pack_up),null,null,null);
        }else {
            infoDown.setVisibility(View.VISIBLE);
            decription.setMaxLines(2);
            decription.setEllipsize(TextUtils.TruncateAt.END);
            infoDown.setText("完全简介");
            infoDown.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.gold_lecture_down),null,null,null);

        }
    }

    private void infoNotify() {
        if ("OK".equals(infoBean.getCode())) {

            GoldLectureInfoBean.ResultBean resultBean = infoBean.getResult();
            if (resultBean != null) {
                title.setText(resultBean.getNickName());
                headName.setText(resultBean.getNickName());
                decription.setText(resultBean.getPersonalProfile());

                decription.setMaxLines(Integer.MAX_VALUE);
                decription.setEllipsize(null);
                decription.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {

                        if (!flag){
                            return;
                        }
                        flag = false;

                        if (decription.getLineCount() < 3) {
                            infoDown.setVisibility(View.GONE);
                        } else {
                            decription.setMaxLines(2);
                            infoDown.setVisibility(View.VISIBLE);
                            infoDown.setText("完全简介");
                            decription.setEllipsize(TextUtils.TruncateAt.END);
                        }

                    }
                });

                headView.setImageURI(Utils.getImgUri(resultBean.getPortrait() + ImgFilter.SSCC_H200));
                List<Integer> integers = new ArrayList<>();
                for (GoldLectureInfoBean.ResultBean.IdentificationBean mIdentificationEntity : resultBean.getIdentification()) {
                    integers.add(Integer.valueOf(mIdentificationEntity.getId()));
                }
                memberType = StrUtil.checkUserType(integers);

                for (Integer vipId : integers) {
                    switch (vipId) {
                        case 1:
                            vipImage1.setVisibility(View.VISIBLE);
                            break;
                        case 2:
                            vipImage2.setVisibility(View.VISIBLE);
                            break;
                        case 3:
                            vipImage3.setVisibility(View.VISIBLE);
                            break;
                    }
                }

                if (memberType >= 8) {
                    headLevel.setText(StrUtil.getMemberType(memberType));
                    headLevel.setBackgroundResource(R.drawable.label_yellow_shape);
                } else if (memberType < 8 && memberType >= 5) {

                    headLevel.setText(StrUtil.getMemberType(memberType));
                    switch (memberType) {

                        case 5:
                            headLevel.setBackgroundResource(R.drawable.label_yellow_shape);
                            break;
                        case 6:
                            headLevel.setBackgroundResource(R.drawable.label_orange_shape);
                            break;
                        case 7:
                            headLevel.setBackgroundResource(R.drawable.label_green_shape);
                            break;
                    }
                } else if (memberType == 4) {
                    headLevel.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.gold_teacher_identify), null, null, null);
                    headLevel.setText("认证");
                } else {
                    headLevel.setVisibility(View.GONE);
                }

                String kindergartenName = "";
                String kindergartenNo = "";
                if (integers.contains(5)) {
                    if (resultBean.getEduInstitutions() != null && resultBean.getEduInstitutions().size() > 0) {
                        kindergartenNo = resultBean.getEduInstitutions().get(0).getId();
                        kindergartenName = resultBean.getEduInstitutions().get(0).getName();
                    }
                } else {
                    if (resultBean.getKids() != null && resultBean.getKids().size() > 0) {

                        kindergartenNo = String.valueOf(resultBean.getKids().get(0).getKindergartenId());
                        kindergartenName = resultBean.getKids().get(0).getKindergartenName();
                        headName.setText(resultBean.getNickName() + "·宝宝" + resultBean.getKids().get(0).getAge() + " 岁");

                    }
                }

                if (resultBean.getIdentification() != null) {
                    for (GoldLectureInfoBean.ResultBean.IdentificationBean bean : resultBean.getIdentification()) {
                        if (bean.getId().equals(String.valueOf(memberType))) {

//                                personalIntroTxt.setText(bean.getIntroduction());
                        }
                    }
                }

                if (TextUtils.isEmpty(kindergartenName)) {

                    kindergartenNameTxt.setVisibility(View.GONE);

                } else {
                    kindergartenNameTxt.setVisibility(View.VISIBLE);
                    kindergartenNameTxt.setText(kindergartenName);
                }
                List<String> personalPhotos = resultBean.getPhotos();
                if (personalPhotos == null || personalPhotos.size() == 0) {
                    albumRecycleLayout.setVisibility(View.GONE);
                } else if (personalPhotos.size() <= 4) {
                    isShow4 = false;
                    list4.clear();
                    list4.addAll(personalPhotos);
                    list.addAll(personalPhotos);
                    albumRecycleLayout.setVisibility(View.VISIBLE);
                    albumRecyle4.setVisibility(View.VISIBLE);
                    albumRecycleFull.setVisibility(View.GONE);
                    album4Adapter.setShow4(isShow4);
                    album4Adapter.notifyDataSetChanged();

                } else {
                    isShow4 = true;
                    list.clear();
                    list.addAll(personalPhotos);
                    albumRecycleLayout.setVisibility(View.VISIBLE);
                    albumRecyle4.setVisibility(View.VISIBLE);
                    albumRecycleFull.setVisibility(View.GONE);
                    for (int i = 0; i < personalPhotos.size(); i++) {
                        if (i < 4) {
                            list4.add(personalPhotos.get(i));
                        }
                    }
                    album4Adapter.setShow4(isShow4);
                    album4Adapter.notifyDataSetChanged();
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }


    private void getUserInfo() {

        String currentTime = String.valueOf(Utils.getCurrentTimeMillis());
        HashMap<String, String> valueData = new HashMap<>();
        valueData.put("time", currentTime);
        valueData.put("Fid", fid);
        HttpMehtod.getInstance().getGoldLectureInfo(valueData, new Subscriber<Response<ResponseBody>>() {

            @Override
            public void onStart() {
                super.onStart();
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
            }

            @Override
            public void onCompleted() {

                dialog.dismiss();
                infoNotify();
            }

            @Override
            public void onError(Throwable e) {
                dialog.dismiss();
            }

            @Override
            public void onNext(Response<ResponseBody> o) {

                String result = NetUtil.getResResult(o);
                Gson gson = new Gson();
                infoBean = gson.fromJson(result, GoldLectureInfoBean.class);

            }
        });

    }

    private void getStoryData() {
        String time = String.valueOf(Utils.getCurrentTimeMillis());
        Map<String, String> valueData = new HashMap<>();
        valueData.put("PageIndex", String.valueOf(PageIndex));
        valueData.put("FancyId", fid);
        valueData.put("time", time);
        HttpMehtod.getInstance().getGoldLecutreStory(valueData, new Subscriber<Response<ResponseBody>>() {

            @Override
            public void onStart() {
                super.onStart();
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
            }

            @Override
            public void onCompleted() {

                dialog.dismiss();
            }

            @Override
            public void onError(Throwable e) {

                dialog.dismiss();
            }

            @Override
            public void onNext(Response<ResponseBody> o) {

                String result = NetUtil.getResResult(o);
                Gson gson = new Gson();
                FFlibraryStoryBean bean = gson.fromJson(result, FFlibraryStoryBean.class);

                if ("OK".equals(bean.getCode())) {

                    if (PageIndex == 1) {
                        xRefreshView.stopRefresh();
                    } else {
                        xRefreshView.stopLoadMore();
                    }

                    if (bean.getResult() != null && bean.getResult().size() < 10) {
                        xRefreshView.setLoadComplete(true);
                        xRefreshView.setPullLoadEnable(true);
                    }

                    storyList.addAll(bean.getResult());
                    personalAdapter.notifyDataSetChanged();

                }

            }
        });
    }

    private void personalShare() {

        String shareTitle = "";
        final String contentStr = infoBean.getResult().getPersonalProfile();
        final String picUrl = Utils.getImgUrlUtil(infoBean.getResult().getPortrait() + ImgFilter.SSCC_H200);
        String shareId = infoBean.getResult().getFid();
        final String webPageUrl = Utils.getUrlIndex("PersonIndex-Share")+"?fid=" + shareId;

        switch (memberType) {
            case 5:
            case 6:
            case 7:
                if (infoBean.getResult().getNickName().equals(LoginUserSharePrefernce.getName())) {
                    shareTitle = "我是" + infoBean.getResult().getNickName() + "老师,我在凡学为孩子讲故事，点亮孩子的阅读之光。";
                } else if (!infoBean.getResult().getNickName().equals(LoginUserSharePrefernce.getName()) || TextUtils.isEmpty(LoginUserSharePrefernce.getName())) {
                    shareTitle = infoBean.getResult().getNickName() + "老师在凡学为孩子讲故事，点亮孩子的阅读之光。";
                }
                break;
            default:
                if (infoBean.getResult().getNickName().equals(LoginUserSharePrefernce.getName())) {
                    shareTitle = "我是" + infoBean.getResult().getNickName() + "老师,我在凡学为孩子讲故事，点亮孩子的阅读之光。";
                } else if (!infoBean.getResult().getNickName().equals(LoginUserSharePrefernce.getName()) || TextUtils.isEmpty(LoginUserSharePrefernce.getName())) {
                    shareTitle = infoBean.getResult().getNickName() + "老师在凡学为孩子讲故事，点亮孩子的阅读之光。";
                }
                break;

        }


        SharePopupWindow sharePopupWindow = new SharePopupWindow(this, goldLectureRecycle);
        final String finalShareTitle = shareTitle;
        sharePopupWindow.setShareCallBack(new SharePopupWindow.ShareCallBack() {
            @Override
            public void wxCallBack() {

                WXShareUtil.getInstance(GoldLecturerActivity.this).shareWebPage(picUrl, finalShareTitle, contentStr, webPageUrl, false);
            }

            @Override
            public void wxFriendCallBack() {
                WXShareUtil.getInstance(GoldLecturerActivity.this).shareWebPage(picUrl, finalShareTitle, contentStr, webPageUrl, true);
            }
        });
        sharePopupWindow.showPopupWindow();

    }


    private void initView() {
        dialog = ProgressUtil.creatRequestDialog(this, "正在发送电波");
        title.setText("姓名");
        rightImg.setImageResource(R.mipmap.share);
        rightImg.setVisibility(View.VISIBLE);
        rightImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (infoBean != null) {
                    personalShare();
                }
            }
        });
        topView = getLayoutInflater().inflate(R.layout.gold_lecturer_personal_head, null);
        headView = (SimpleDraweeView) topView.findViewById(R.id.headerIcon);
        headName = (TextView) topView.findViewById(R.id.headerName);
        decription = (TextView) topView.findViewById(R.id.personal_info);
        headLevel = (TextView) topView.findViewById(R.id.lecture_level_text);
        kindergartenNameTxt = (TextView) topView.findViewById(R.id.txt_personal_kindergarten);
        vipImage1 = (ImageView) topView.findViewById(R.id.img_vip1);
        vipImage2 = (ImageView) topView.findViewById(R.id.img_vip2);
        vipImage3 = (ImageView) topView.findViewById(R.id.img_vip3);
        infoDown = (TextView) topView.findViewById(R.id.total_intro_image);
        albumRecycleFull = (RecyclerView) topView.findViewById(R.id.album_full_recycle);
        albumRecyle4 = (RecyclerView) topView.findViewById(R.id.album_4_recycle);
        albumRecycleLayout = (FrameLayout) topView.findViewById(R.id.album_recycle_layout);

        infoDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    isExpand();
            }
        });

    }

    private void initRecycle() {

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        goldLectureRecycle.setLayoutManager(manager);
        personalAdapter = new GoldLecturePersonalAdapter(this, nickName, storyList);
        goldLectureRecycle.setAdapter(personalAdapter);
        personalAdapter.setHeaderView(topView, goldLectureRecycle);


        adapter = new GoldLectureInfoAlbumAdapter(this, isShow4, list, new AlbumImpl() {
            @Override
            public void onClick(int position) {

                albumRecyle4.setVisibility(View.VISIBLE);
                albumRecycleFull.setVisibility(View.GONE);
            }
        });

        GridLayoutManager layoutManager = new GridLayoutManager(this, 4);
        layoutManager.setOrientation(GridLayoutManager.VERTICAL);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL);
        dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.album_borde));
        albumRecycleFull.addItemDecoration(dividerItemDecoration);
        albumRecycleFull.setLayoutManager(layoutManager);
        albumRecycleFull.setAdapter(adapter);

        GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 4);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        DividerItemDecoration dividerItemDecoration2 = new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL);
        dividerItemDecoration2.setDrawable(getResources().getDrawable(R.drawable.album_borde));
        albumRecyle4.addItemDecoration(dividerItemDecoration2);
        albumRecyle4.setLayoutManager(linearLayoutManager);
        album4Adapter = new Album4Adapter(this, isShow4, list, list4, new AlbumImpl() {
            @Override
            public void onClick(int position) {

                albumRecyle4.setVisibility(View.GONE);
                albumRecycleFull.setVisibility(View.VISIBLE);
            }
        });

        albumRecyle4.setAdapter(album4Adapter);


    }


    private void initXRefresh() {
        xRefreshView.setPullLoadEnable(true);

        personalAdapter.setCustomLoadMoreView(new CustomFootView(this));

        xRefreshView.setCustomHeaderView(new CustomHeaderView(this));
        xRefreshView.setPinnedTime(1000);
        xRefreshView.setXRefreshViewListener(new XRefreshView.XRefreshViewListener() {
            @Override
            public void onRefresh() {
                if (personalAdapter.audioPlayer != null){

                    personalAdapter.audioPlayer.stop();
                }
                PageIndex = 1;
                storyList.clear();
                list.clear();
                list4.clear();
                getStoryData();
                getUserInfo();
            }

            @Override
            public void onRefresh(boolean isPullDown) {

            }

            @Override
            public void onLoadMore(boolean isSilence) {

                PageIndex++;
                getStoryData();
            }

            @Override
            public void onRelease(float direction) {

            }

            @Override
            public void onHeaderMove(double headerMovePercent, int offsetY) {

            }
        });
    }
}
